package com.delamer.facile.exe;

import com.delamer.facile.db.DBUtilWarp;
import com.delamer.facile.obj.ObjectWarp;
import com.delamer.utils.ItemUtil;
import com.delamer.utils.MsgUtil;
import com.delamer.utils.PermitUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExecutorWarp {

    public void help(CommandSender sender, String[] args) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Bukkit.getPluginManager().getPlugin("DelamerFacile").getResource("warp.help"), "UTF-8"));
        List<String> results = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null)
            results.add(line);
        sender.sendMessage(results.toArray(new String[]{}));
    }

    public void menu(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        YamlConfiguration config = YamlConfiguration.loadConfiguration(new File(Bukkit.getPluginManager().getPlugin("DelamerFacile").getDataFolder(), "menu-warp.yml"));
        int size = config.getInt("menu.size");
        if (size < 1 || size > 6) {
            sender.sendMessage(MsgUtil.err("菜单打开失败 -> 尺寸配置错误"));
            return;
        } else {
            size *= 9;
        }
        Inventory inventory = Bukkit.createInventory(null, size, config.getString("menu.title"));
        ItemStack errorMenuItem = ItemUtil.createMenuItem(Bukkit.getPluginManager().getPlugin("DelamerFacile"), config.getString("menu.error.item").toUpperCase(), config.getString("menu.error.name"));
        if (errorMenuItem == null) {
            sender.sendMessage(MsgUtil.err("菜单打开失败 -> 填充栏配置错误:加载失败栏"));
            return;
        }
        ItemStack emptyMenuItem = ItemUtil.createMenuItem(Bukkit.getPluginManager().getPlugin("DelamerFacile"), config.getString("menu.empty.item").toUpperCase(), config.getString("menu.empty.name"));
        if (emptyMenuItem == null) {
            sender.sendMessage(MsgUtil.err("菜单打开失败 -> 填充栏配置错误：空栏"));
            return;
        }
        for (int i = 0; i < size; i++) {
            String prefix = "menu." + (i + 1);
            if (config.contains(prefix)) {
                ItemStack currentMenuItem = ItemUtil.createMenuItem(Bukkit.getPluginManager().getPlugin("DelamerFacile"), config.getString(prefix + ".item").toUpperCase(), config.getString(prefix + ".name"));
                if (currentMenuItem != null) {
                    if (config.contains(prefix + ".event")) {
                        Map<String, String> map = new HashMap<String, String>();
                        if (config.contains(prefix + ".event.all"))
                            map.put("AllClickEvent", config.getString(prefix + ".event.all"));
                        if (config.contains(prefix + ".event.left"))
                            map.put("LeftClickEvent", config.getString(prefix + ".event.left"));
                        if (config.contains(prefix + ".event.shift_left"))
                            map.put("ShiftLeftClickEvent", config.getString(prefix + ".event.shift_left"));
                        if (config.contains(prefix + ".event.right"))
                            map.put("RightClickEvent", config.getString(prefix + ".event.right"));
                        if (config.contains(prefix + ".event.shift_right"))
                            map.put("ShiftRightClickEvent", config.getString(prefix + ".event.shift_right"));
                        if (config.contains(prefix + ".event.middle"))
                            map.put("MiddleClickEvent", config.getString(prefix + ".event.middle"));
                        if (config.contains(prefix + ".event.drop"))
                            map.put("DropClickEvent", config.getString(prefix + ".event.drop"));
                        if (config.contains(prefix + ".event.ctrl_drop"))
                            map.put("CtrlDropClickEvent", config.getString(prefix + ".event.ctrl_drop"));
                        currentMenuItem = ItemUtil.addEvent(Bukkit.getPluginManager().getPlugin("DelamerFacile"), currentMenuItem, map);
                    }
                    if (config.contains(prefix + ".lore")) {
                        currentMenuItem = ItemUtil.addLore(Bukkit.getPluginManager().getPlugin("DelamerFacile"), currentMenuItem, config.getStringList(prefix + ".lore"));
                    }
                    inventory.setItem(i, currentMenuItem);
                } else {
                    inventory.setItem(i, errorMenuItem);
                }
            } else {
                inventory.setItem(i, emptyMenuItem);
            }
        }
        ((Player) sender).openInventory(inventory);
    }

    public void list(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        String msg = "§e地标列表：§f";
        List<ObjectWarp> list = DBUtilWarp.getWarpList();
        if (list.size() == 0) {
            msg = msg + "无";
        } else {
            for (ObjectWarp objectWarp : list) msg = msg + objectWarp.getWarpName() + ", ";
            msg = msg.substring(0, msg.length() - 2);
        }
        sender.sendMessage(msg);
    }

    public void info(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入地标名称"));
            return;
        }
        ObjectWarp objectWarp = DBUtilWarp.getWarp(args[1]);
        if (objectWarp == null) {
            sender.sendMessage(MsgUtil.err("地标不存在"));
            return;
        }
        String msg = "§e地标信息：§f";
        msg = msg.concat("\n - §b名称：§f" + objectWarp.getWarpName());
        msg = msg.concat("\n - §b世界：§f" + objectWarp.getWorldName());
        msg = msg.concat("\n - §bX：§f" + objectWarp.getLocationX());
        msg = msg.concat("\n - §bY：§f" + objectWarp.getLocationY());
        msg = msg.concat("\n - §bZ：§f" + objectWarp.getLocationZ());
        sender.sendMessage(msg);
    }

    public void add(CommandSender sender, String[] args) throws Exception {
        if (!sender.isOp()) {
            sender.sendMessage(MsgUtil.err("无OP权限的玩家无法使用该指令"));
            return;
        }
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入地标名称"));
            return;
        }
        try {
            if (DBUtilWarp.getWarp(args[1]) != null) {
                sender.sendMessage(MsgUtil.err("地标已存在"));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("添加地标失败->检查地标是否存在时发生错误"));
            return;
        }
        try {
            Location location = ((Player) sender).getLocation();
            ObjectWarp objectWarp = new ObjectWarp() {{
                setWarpName(args[1]);
                setWorldName(location.getWorld().getName());
                setLocationX(String.valueOf((int) location.getX()));
                setLocationY(String.valueOf((int) location.getY()));
                setLocationZ(String.valueOf((int) location.getZ()));
            }};
            boolean isAdd = DBUtilWarp.addWarp(objectWarp);
            if (isAdd) {
                sender.sendMessage(MsgUtil.msg("添加地标成功：§b" + args[1]));
            } else {
                sender.sendMessage(MsgUtil.err("添加地标失败->未能添加地标到数据库"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("添加地标失败->添加地标时发生错误"));
        }
    }

    public void set(CommandSender sender, String[] args) throws Exception {
        if (!sender.isOp()) {
            sender.sendMessage(MsgUtil.err("无OP权限的玩家无法使用该指令"));
            return;
        }
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入地标名称"));
            return;
        }
        try {
            if (DBUtilWarp.getWarp(args[1]) == null) {
                sender.sendMessage(MsgUtil.err("地标不存在"));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("更新地标失败->检查地标是否存在时发生错误"));
            return;
        }
        try {
            Location location = ((Player) sender).getLocation();
            ObjectWarp objectWarp = new ObjectWarp() {{
                setWarpName(args[1]);
                setWorldName(location.getWorld().getName());
                setLocationX(String.valueOf((int) location.getX()));
                setLocationY(String.valueOf((int) location.getY()));
                setLocationZ(String.valueOf((int) location.getZ()));
            }};
            boolean isSet = DBUtilWarp.setWarp(objectWarp);
            if (isSet) {
                sender.sendMessage(MsgUtil.msg("更新地标成功：§b" + args[1]));
            } else {
                sender.sendMessage(MsgUtil.err("更新地标失败->未能更新数据库的地标"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("更新地标失败->更新地标时发生错误"));
        }
    }

    public void del(CommandSender sender, String[] args) throws Exception {
        if (!sender.isOp()) {
            sender.sendMessage(MsgUtil.err("无OP权限的玩家无法使用该指令"));
            return;
        }
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入地标名称"));
            return;
        }
        try {
            if (DBUtilWarp.getWarp(args[1]) == null) {
                sender.sendMessage(MsgUtil.err("地标不存在"));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("删除地标失败->检查地标是否存在时发生错误"));
            return;
        }
        try {
            ObjectWarp objectWarp = new ObjectWarp() {{
                setWarpName(args[1]);
            }};
            boolean isDel = DBUtilWarp.delWarp(objectWarp);
            if (isDel) {
                sender.sendMessage(MsgUtil.msg("删除地标成功：§b" + args[1]));
            } else {
                sender.sendMessage(MsgUtil.err("删除地标失败->未能从数据库删除地标"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            sender.sendMessage(MsgUtil.err("删除地标失败->删除地标时发生错误"));
        }
    }

    public void tp(CommandSender sender, String[] args) throws Exception {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MsgUtil.err("该指令无法通过控制台使用"));
            return;
        }
        if(!PermitUtil.hasPermit(sender.getName(),"warp.tp")){
            sender.sendMessage(MsgUtil.err("未取得授权的玩家无法使用该指令"));
            return;
        }
        if (args.length < 2) {
            sender.sendMessage(MsgUtil.err("请输入地标名称"));
            return;
        }
        ObjectWarp objectWarp = DBUtilWarp.getWarp(args[1]);
        if (objectWarp == null) {
            sender.sendMessage(MsgUtil.err("地标不存在"));
            return;
        }
        try {
            Location location = new Location(Bukkit.getWorld(objectWarp.getWorldName()), Double.valueOf(objectWarp.getLocationX()), Double.valueOf(objectWarp.getLocationY()), Double.valueOf(objectWarp.getLocationZ()));
            ((Player) sender).teleport(location);
            sender.sendMessage(MsgUtil.msg("地标传送成功：§6" + objectWarp.getWarpName()));
        } catch (Exception e) {
            sender.sendMessage(MsgUtil.err("地标传送失败"));
        }
    }
}
